/*
 * @Descripttion:  axios封装
 * @version: 
 * @Author: hzx
 * @Date: 2021-03-03 00:05:42
 * @LastEditors: hzx
 * @LastEditTime: 2021-03-26 21:51:52
 */

import axios from "axios";
import qs from "qs";

const config = {
    baseURL: "/api",
    contentType: "application/json;charset=UTF-8",
    requestTimeout: 10000,
}

/**
 * @author hzx 195924137@qq.com
 * @description axios初始化
 */
const instance = axios.create({
    baseURL: config["baseURL"],
    timeout: config["requestTimeout"],
    headers: { 'Content-Type': config["contentType"]},
})

/**
 * @author hzx 195924137@qq.com
 * @description axios请求拦截器
 */
instance.interceptors.request.use(
    (config) => {
        if (config.data && config.headers['Content-Type'] === config.contentType)
            config.data = qs.stringify(config.data)
        return config
    },
    (error) => Promise.reject(error)
)

/**
 * @author hzx 195924137@qq.com
 * @description axios拦截响应器
 */
instance.interceptors.response.use(
    (response) => {
        const { data: responseData } = response
        // {
        //     result, // true/false
        //     code, // Number | 各种错误编码
        //     data, // 返回的数据包
        //     message // 前端对code的中文译解（不能直接拿来用）
        // }
        const { result, code, message, data } = responseData;
        // 是否操作正常
        if (result === true) return data;
        // 异常解构抛出
        return Promise.reject({ code, message, data })
    },
    (error) => {
        const { response } = error
        if (!response || !response.data) {
            let { message } = error
            if (message === 'Network Error') {
                message = '后端接口连接异常'
            }
            if (message.includes('timeout')) {
                message = '后端接口请求超时'
            }
            if (message.includes('Request failed with status code')) {
                const code = message.substr(message.length - 3)
                message = '后端接口' + code + '异常'
            }
            //console.log(message || `后端接口未知异常`)
        }
        return Promise.reject(error)
    }
)

/**
 * @name: 封装get请求
 * @msg: 
 * @param {*} url  请求接口地址
 * @param {*} params 请求参数
 * @return {*}
 */
export function get(url, params) {
    return new Promise(resolve => {
        instance({ url, method: "Get", params }).then(
            (response) => resolve([response, null])
        ).catch(
            (error) => resolve([null, error])
        )
    })
}

/**
 * @name: 封装post请求
 * @msg: 
 * @param {*} url  请求接口地址
 * @param {*} data 请求数据默认 json
 * @return {*}
 */
export function post(url, data) {
    return new Promise(resolve => {
        instance({ url, method: "Post", data }).then(
            (response) => resolve([response, null])
        ).catch(
            (error) => resolve([null, error])
        )
    })
}

